package com.richpencil.modules.service.impl;
import cn.hutool.core.lang.Dict;
import cn.hutool.json.JSONObject;
import com.richpencil.modules.ki.domain.Log;
import com.richpencil.modules.repository.LogRepository;
import com.richpencil.modules.service.LogService;
import com.richpencil.modules.service.mapper.LogErrorMapper;
import com.richpencil.modules.service.mapper.LogSmallMapper;
import com.richpencil.modules.service.dto.LogQueryCriteria;
import com.richpencil.utils.DateUtils;
import com.richpencil.utils.PageUtil;
import com.richpencil.utils.QueryHelp;
import com.richpencil.utils.StringUtils;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import java.lang.reflect.Method;

/** 
 *
 * @date 2018-11-24
 */
@Service
@Transactional(propagation = Propagation.SUPPORTS, readOnly = true, rollbackFor = Exception.class)

public class LogServiceImpl implements LogService {
  
    @Autowired
    private LogRepository logRepository;

    @Autowired
    private LogErrorMapper logErrorMapper;

    @Autowired
    private LogSmallMapper logSmallMapper;

    private final String LOGINPATH = "login";

    @Override
    public Object queryAll(LogQueryCriteria criteria, Pageable pageable){
        Page<Log> page = logRepository.findAll(((root, criteriaQuery, cb) -> QueryHelp.getPredicate(root, criteria, cb)),pageable);
        if ("ERROR".equals(criteria.getLogType())) {
            return PageUtil.toPage(page.map(logErrorMapper::toDto));
        }
        return page;
    }

    @Override
    public Object queryAllByUser(LogQueryCriteria criteria, Pageable pageable) {
        Page<Log> page = logRepository.findAll(((root, criteriaQuery, cb) -> QueryHelp.getPredicate(root, criteria, cb)),pageable);
        return PageUtil.toPage(page.map(logSmallMapper::toDto));
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void save(String username, String ip, ProceedingJoinPoint joinPoint, Log log){
        try {
            MethodSignature signature = (MethodSignature) joinPoint.getSignature();
            Method method = signature.getMethod();
            com.richpencil.modules.log.Log aopLog = method.getAnnotation(com.richpencil.modules.log.Log.class);

            // 描述
            if (log != null) {
                log.setDescription(aopLog.value());
            }

            // 方法路径
            String methodName = joinPoint.getTarget().getClass().getName()+"."+signature.getName()+"()";

            String params = "{";
            //参数值
            Object[] argValues = joinPoint.getArgs();
            //参数名称
            String[] argNames = ((MethodSignature)joinPoint.getSignature()).getParameterNames();
            if(argValues != null){
                for (int i = 0; i < argValues.length; i++) {
                    params += " " + argNames[i] + ": " + argValues[i];
                }
            }

            // 获取IP地址
            log.setRequestIp(ip);

            if(LOGINPATH.equals(signature.getName())){
                try {
                    JSONObject jsonObject = new JSONObject(argValues[0]);
                    username = jsonObject.get("username").toString();
                }catch (Exception e){
                    e.printStackTrace();
                }
            }
            log.setAddress(trimLog(StringUtils.getCityInfo(log.getRequestIp())));
            log.setMethod(trimLog(methodName));
            log.setUsername(trimLog(username));
            log.setParams(trimLog(params + " }"));
            log.setCreateTime(trimLog(DateUtils.GetCurrentDateTime()));
            logRepository.save(log);
        }
        catch (Exception ex){
            System.out.println(ex.toString());
        }
    }

    private String trimLog(String value){
        return value.replaceAll("\0", "");
    }


    @Override
    public Object findByErrDetail(String id) {
        return Dict.create().set("exception",logRepository.findExceptionById(id)); 
    }
}
